/***********************************************************
 *
 * Gaoth
 * Copyright (c) 2011- Marcus Lundgren
 * 
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from
 * the use of this software.
 * 
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it freely,
 * subject to the following restrictions:
 *
 *  1. The origin of this software must not be misrepresented; you must not
 *     claim that you wrote the original software. If you use this software
 *     in a product, an acknowledgment in the product documentation would be
 *     appreciated but is not required.
 *
 *  2. Altered source versions must be plainly marked as such,
 *     and must not be misrepresented as being the original software.
 *
 *  3. This notice may not be removed or altered from any source distribution.
 *
 ***********************************************************/

#pragma once

#include <SFML/System.hpp>
#include <SFML/Network.hpp>

#include "../model/model.h"

#include <gaoth-shared/network/packet_manager.h>

/**
 * Handles the network I/O between the clients and the server.
 */
class NetworkManager
{
public:
    /**
     * Constructor.
     * 
     * @param model
     **/
    NetworkManager( Model *model );
    /**
     * Destructor.
     **/
    virtual ~NetworkManager();
    /**
     * Take care of the packets recieved and the connections made from clients.
     **/
    void update();
    /**
     * Send updates to the connected clients about the state of the model.
     */
    void send_updates();
    /**
     * Send the payload.
     *
     * @param payload the payload to send
     * @param client_id the id of the recipient
     */
    void send( const gth::shared::network::BasePayload *payload, const int client_id  );
    /**
     * Returns the selector.
     * 
     * @return sf::SelectorTCP& the selector
     */
    inline sf::SocketSelector& get_selector();
    
private:
    /**
     * The socket that listens to and sends updates from the clients.
     */
    sf::TcpListener _listener;
    /**
     * Contains the connected sockets.
     */
    sf::SocketSelector _selector;
    /**
     * Pointer to model.
     */
    Model *_model;
    /**
     * Used to thread safe the network manager instance.
     */
    sf::Mutex _lock;
    /**
     *
     */
    gth::shared::network::PacketManager _pkt_mgr;
  
    // Illegal
    NetworkManager();
    NetworkManager( const NetworkManager& );
    NetworkManager& operator=( const NetworkManager & );
};
